/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufjf.posjava.cm.controller.action.agenda;

import br.ufjf.posjava.cm.model.Agenda;
import br.ufjf.posjava.cm.model.DAO.AgendaDAO;
import br.ufjf.posjava.cm.model.Paciente;
import br.ufjf.posjava.cm.model.Profissional;
import br.ufjf.posjava.cm.util.ClinicaMorpheusException;
import br.ufjf.posjava.cm.util.TrataDatas;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

/**
 *
 * @author Filipe
 */
@WebServlet(name = "GravaAgendaAction", urlPatterns = {"/GravaAgendaAction"})
public class GravaAgendaAction extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int paciente = Integer.parseInt(request.getParameter("cpPaciente"));
        int dentista = Integer.parseInt(request.getParameter("cpDentista"));
        int atendente = Integer.parseInt(request.getParameter("cpAtendente"));
        String status = "agendada";

        String btn = request.getParameter("btn");

        if (btn.equalsIgnoreCase("Gravar")) {

            Agenda agenda = new Agenda();
            try {
                Date data = TrataDatas.strToDate(request.getParameter("cpData")+" "+request.getParameter("cpHorario"));
                agenda.setData(data);
                agenda.setPaciente(new Paciente(paciente));
                agenda.setDentista(new Profissional(dentista));
                agenda.setAtendente(new Profissional(atendente));
                agenda.setStatus(status);

                if (validar(agenda)) {
                    new AgendaDAO().inserir(agenda);
                }
                request.setAttribute("msg", "Consulta agendada com sucesso!");
                RequestDispatcher rd = request.getRequestDispatcher("ListarAgendaAction");
                rd.forward(request, response);
            } catch (ClinicaMorpheusException ex) {  //Minha Exceçao              
                RequestDispatcher rd = request.getRequestDispatcher("NovaAgendaAction");
                request.setAttribute("msg", ex.getMessage());
                rd.forward(request, response);
            } catch (ClassNotFoundException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            } catch (SQLException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("NovaAgendaAction");
                request.setAttribute("msg", ex.getSQLState());
                rd.forward(request, response);
            } catch (ParseException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            }

        } else if (btn.equalsIgnoreCase("Alterar")) {
            int idAgenda = Integer.parseInt(request.getParameter("idAgenda"));
            Agenda agenda;
            try {
                Date data = TrataDatas.strToDate(request.getParameter("cpData")+" "+request.getParameter("cpHorario"));
                
                agenda = new Agenda(idAgenda, data, new Paciente(paciente), new Profissional(dentista), new Profissional(atendente), status);
                 
                if (validar(agenda)) {
                    new AgendaDAO().alterar(agenda);
                }
                request.setAttribute("msg", "Agendamento alterado com sucesso!");
                RequestDispatcher rd = request.getRequestDispatcher("ListarAgendaAction");
                rd.forward(request, response);
            } catch (ClinicaMorpheusException ex) {  //Minha Exceçao              
                RequestDispatcher rd = request.getRequestDispatcher("AlteraAgendaAction");
                request.setAttribute("msg", ex.getMessage());
                rd.forward(request, response);
            } catch (ClassNotFoundException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            } catch (SQLException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("AlteraAgendaAction");
                request.setAttribute("msg", ex.getSQLState());
                rd.forward(request, response);
            } catch (ParseException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            }

        } else {
            //Abaixo a função do botão cancelar
            RequestDispatcher rd = request.getRequestDispatcher("ListarAgendaAction");
            rd.forward(request, response);
        }

    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean validar(Agenda agenda) throws ClinicaMorpheusException, ClassNotFoundException, SQLException, ParseException {
        Date dataAtual = new Date();
        Date dataEscolhida = agenda.getData();
        
        if(dataEscolhida.getTime() < dataAtual.getTime()){
            throw new ClinicaMorpheusException("Esta data e horário já passaram."); 
        }
        if (agenda.getPaciente().getIdPaciente() < 0) {
            throw new ClinicaMorpheusException("O paciente deve ser informado.");
        }
        if (agenda.getDentista().getIdProfissional() < 0) {
            throw new ClinicaMorpheusException("O dentista deve ser informado.");
        }        
        return true;
    }
}
